package cn.mrlong.usbcamera.view;

import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.Toast;

import com.jiangdg.usbcamera.UVCCameraHelper;
import com.jiangdg.usbcamera.utils.FileUtils;
import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.Size;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.common.AbstractUVCCameraHandler;
import com.serenegiant.usb.encoder.RecordParams;
import com.serenegiant.usb.widget.CameraViewInterface;
import com.serenegiant.usb.widget.UVCCameraTextureView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.mrlong.usbcamera.R;
import cn.mrlong.usbcamera.application.MyApplication;
import cn.mrlong.usbcamera.utils.CircularProgressDialog;

import org.easydarwin.easyrtmp.push.EasyRTMP;
import org.easydarwin.push.InitCallback;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * UVCCamera use demo
 * <p>
 * Created by jiangdongguo on 2017/9/30.
 */

public class USBCameraActivity extends AppCompatActivity implements CameraDialog.CameraDialogParent, CameraViewInterface.Callback {
    private static final String TAG = "Debug";
    private UVCCameraHelper mCameraHelper;
    private UVCCameraTextureView mUVCCameraView;
    private boolean isRequest;
    private boolean isPreview;
    private String rtmp_url = "rtmp://49.4.1.108:19350/t/9900000005";
    private final static String ACTION_CLOSE_USB_CAMERA = "android.intent.concox.action.ACTION_CLOSE_USB_CAMERA";
    private final static String ACTION_SHOW_USB_CAMERA = "android.intent.concox.action.ACTION_SHOW_USB_CAMERA";
    private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {

        @Override
        public void onAttachDev(UsbDevice device) {
            if (mCameraHelper == null || mCameraHelper.getUsbDeviceCount() == 0) {
                showShortMsg("check no usb camera");
                return;
            }
            // request open permission
            if (!isRequest) {
                isRequest = true;
                if (mCameraHelper != null) {
                    mCameraHelper.requestPermission(0);
                }
            }
        }

        @Override
        public void onDettachDev(UsbDevice device) {
            // close camera
            if (isRequest) {
                isRequest = false;
                mCameraHelper.closeCamera();
                showShortMsg(device.getDeviceName() + " is out");
            }
        }

        @Override
        public void onConnectDev(UsbDevice device, boolean isConnected) {
            if (!isConnected) {
                showShortMsg("fail to connect,please check resolution params");
                isPreview = false;
            } else {
                isPreview = true;
                showShortMsg("connecting");
                startPush();
            }
        }

        @Override
        public void onDisConnectDev(UsbDevice device) {
            showShortMsg("disconnecting");
        }
    };
    private EasyRTMP easyRTMP;
    private boolean isConn = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 3000:
                    closeDialog();
                    goBack();
                    break;
                case 3001:

                    break;
            }
        }
    };
    private Thread after5s_background;
    private CircularProgressDialog circularProgressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usbcamera);
        EventBus.getDefault().register(this);

        // step.1 initialize UVCCameraHelper
        mUVCCameraView = (UVCCameraTextureView) findViewById(R.id.camera_view);
        mUVCCameraView.setCallback(this);
        initCameraHelper();
        initEasyRTMP();
    }

    private void startPush() {
        startPusher();
        showShortMsg("5s进入后台...");
        showDialog();
        after5s_background = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    handler.sendEmptyMessage(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    after5s_background.interrupt();
                }
            }
        };
        after5s_background.start();
    }

    public void showDialog() {
        closeDialog();
        circularProgressDialog = new CircularProgressDialog(this);
        circularProgressDialog.setHintText("5s进入后台...");
        circularProgressDialog.show();
    }

    private void closeDialog() {
        if (null != circularProgressDialog) {
            circularProgressDialog.dismiss();
            circularProgressDialog = null;
        }
    }

    private void initCameraHelper() {
        mCameraHelper = UVCCameraHelper.getInstance();
        mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);

        mCameraHelper.setOnPreviewFrameListener(new AbstractUVCCameraHandler.OnPreViewResultListener() {
            @Override
            public void onPreviewResult(byte[] nv21Yuv) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.sendBroadcast(new Intent(ACTION_CLOSE_USB_CAMERA));
        if (mCameraHelper != null) {
            mCameraHelper.registerUSB();
        } else {
            initCameraHelper();
        }
    }

    public void goBack() {
        mUVCCameraView.setOnbackRun(true);
        moveTaskToBack(true);
    }

    private void initEasyRTMP() {

        try {
            easyRTMP = new EasyRTMP();
            easyRTMP.initPush(rtmp_url,
                    USBCameraActivity.this,
                    new InitCallback() {
                        @Override
                        public void onCallback(int code) {
                            Log.e("====>", code + "");
                            switch (code) {
                                case 1:
                                    Log.e("=====>", "连接中...");
                                    showShortMsg("连接中...");
                                    break;
                                case 2:
                                    Log.e("=====>", "连接成功");
                                    showShortMsg("连接成功...");
                                    isConn = true;
                                    break;
                                case 5:        //推流中
                                    isConn = true;
                                    Log.e("=====>", "推流中");
                                    break;
                                default:
                                    Log.e("=====>", "连接失败");
                                    showShortMsg("连接失败...Code:" + code);
                                    isConn = false;
                                    break;
                            }
                        }
                    }, MyApplication.BUS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        // step.2 register USB event broadcast
    }

    @Override
    protected void onStop() {
        super.onStop();
        // step.3 unregister USB event broadcast
        Log.e("=====>", "stop");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("=====>", "onPause");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e("=====>", "onRestart");
    }

    private void startPusher() {
        if (!mCameraHelper.isRecording()) {
            mCameraHelper.startPusher(new AbstractUVCCameraHandler.OnEncodeResultListener() {
                @Override
                public void onEncodeResult(byte[] data, int offset, int length, long timestamp, int type) {
                    try {
                        if (isConn) {
                            Log.e("=====>", "推送中");
                            easyRTMP.push(data, offset, length, timestamp, type);
                        } else {
                            initEasyRTMP();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onRecordResult(String videoPath) {
                    Log.i(TAG, "videoPath = " + videoPath);
                }
            });
            showShortMsg("start record...");
        } else {
            mCameraHelper.stopRecording();
            showShortMsg("stop record...");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventMsg event) {
        if (UsbReceiver.closeLive.equals(event.getTitle()))
            USBCameraActivity.this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUVCCameraView.setOnbackRun(false);
        FileUtils.releaseFile();
        if (mCameraHelper != null) {
            mCameraHelper.unregisterUSB();
        }
        // step.4 release uvc camera resources
        if (mCameraHelper != null) {
            mCameraHelper.release();
        }
        if (null != easyRTMP) {
            easyRTMP.stop();
        }
        this.sendBroadcast(new Intent(ACTION_SHOW_USB_CAMERA));
        showShortMsg("关闭医疗仓预览");
        EventBus.getDefault().unregister(this);
    }

    private void showShortMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public USBMonitor getUSBMonitor() {
        return mCameraHelper.getUSBMonitor();
    }

    @Override
    public void onDialogResult(boolean canceled) {
        if (canceled) {
            showShortMsg("取消操作");
        }
    }

    public boolean isCameraOpened() {
        return mCameraHelper.isCameraOpened();
    }

    @Override
    public void onSurfaceCreated(CameraViewInterface view, Surface surface) {
        if (!isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.startPreview(mUVCCameraView);
            isPreview = true;
        }
    }

    @Override
    public void onSurfaceChanged(CameraViewInterface view, Surface surface, int width, int height) {

    }

    @Override
    public void onSurfaceDestroy(CameraViewInterface view, Surface surface) {
        if (isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.stopPreview();
            isPreview = false;
        }
    }
}
